const {
  ActivityModel
} = require('../../../utils/activity-model.js')
var activityModel = new ActivityModel()
var timeUtils = require('../../../utils/util.js');
const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    couponDataInfo: {},
    layerModel: false, //活动规则
    activityId: '', //活动id
    startTime: '', //该轮次开始时间
    activityTime: "",
    day: '0',
    hou: '00',
    min: "00",
    sec: "00",
    timerName: "", //计时器名字
    shareImage: "https://oss.kiscloud.net/wechat/images/activity/coupon_logo.png",
    memberId: wx.getStorageSync('memberId') || '',
    merchantId: wx.getStorageSync('merchantId') || '',
    authShow: false,
    nextRoundStartTime: '', //下一轮开始时间
    timeStatus: '', //时间状态   1下一轮时间 2活动已结束 3该轮次结束倒计时 
    dayTime: timeUtils.formatTimeTwo(new Date().getTime(), 'D'),
    getCouponModel: false,
    statusModel: false, //异常弹出层
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      merchantId: options.merchantId || ''
    }, function () {
      this.getActivityInstantDetailt();
    })
  },
  /**
   * 活动详情
   */
  getActivityInstantDetailt() {
    activityModel.activityInstantDetailt({
      merchantId: this.data.merchantId,
      memberId: this.data.memberId
    }).then(res => {
      let activityTime = "";
      let timeStatus = "";
      var nowTime = new Date().getTime(); //现在时间（时间戳）
      var roundEndTime = new Date(res.roundEndTime).getTime();
      var roundStartTime = new Date(res.roundStartTime).getTime();
      var nextRoundStartTime = new Date(res.nextRoundStartTime).getTime();
      if (res.activityStatus == 2) { //活动结束
        timeStatus = 2
        activityTime = ''
      } else if (roundEndTime > nowTime && nowTime > roundStartTime) {
        timeStatus = 3
        activityTime = res.roundEndTime
      } else if (res.hasNext === 1) {
        timeStatus = 1
        activityTime = res.nextRoundStartTime || ''
      } else if (res.hasNext == 0) {
        timeStatus = 2
        activityTime = ''
      }
      let that = this;
      that.setData({
        timeStatus: timeStatus,
        activityTime: activityTime || '',
        activityId: res.activityId || '',
        startTime: timeUtils.formatTimeTwo(res.roundStartTime, 'h:m:s') || '',
        nextRoundStartTime: timeUtils.formatTimeTwo(res.nextRoundStartTime, 'Y/M/D h:m:s') || '',
      }, function () {
        let dayTitle = parseInt(that.data.dayTime) - parseInt(that.data.nextRoundStartTime.substr(8, 2))
        that.setData({
          day: dayTitle == -1 ? '明天' : dayTitle > 26 ? '明天' : '',
          hou: that.data.nextRoundStartTime.substr(11, 2),
          min: that.data.nextRoundStartTime.substr(14, 2),
          sec: that.data.nextRoundStartTime.substr(17, 2),
        })
        if (that.data.activityTime != "") {
          that.countDown()
        }
      })
      wx.setNavigationBarTitle({
        title: res.activityName || ''
      })
      this.setData({
        couponDataInfo: res || {}
      })
    }).catch(err => {
      if (err.status == 500) {
        this.setData({
          statusModel: true
        })
      } else {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 倒计时
  countDown: function () {
    var that = this;
    var nowTime = new Date().getTime(); //现在时间（时间戳）
    var endTime = new Date(that.data.activityTime).getTime(); //结束时间（时间戳）
    var time = (endTime - nowTime) / 1000; //距离结束的毫秒数
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    day = that.timeFormin(day);
    hou = that.timeFormin(hou);
    min = that.timeFormin(min);
    sec = that.timeFormin(sec);
    if (that.data.timeStatus == 3) {
      that.setData({
        day: '',
        hou: that.timeFormat(hou),
        min: that.timeFormat(min),
        sec: that.timeFormat(sec)
      })
    }
    // 每1000ms刷新一次
    if (time > 0) {
      that.setData({
        countDown: true
      })
      that.setData({
        timerName: setTimeout(function () { //这里把setInterval赋值给变量名为timer的变量
          that.countDown()
        }, 1000)
      })
    } else {
      if (time > -1) {
        if (that.data.timeStatus == 1 || that.data.timeStatus == 3) {
          that.getActivityInstantDetailt();
        }
      }
      clearInterval(that.data.timerName);
      that.setData({
        countDown: false
      })
    }
  },
  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },
  /**
   * 是否显示弹出层
   */
  isShowLayer() {
    this.setData({
      layerModel: !this.data.layerModel
    })
  },
  /**
   * 关闭弹出层
   */
  statusClose() {
    this.setData({
      statusModel: false
    })
  },
  /**
   * 领券
   */
  getGiftTake(e) {
    var that = this
    let giftId = e.currentTarget.dataset.id; //卡号
    let giftStatus = e.currentTarget.dataset.name;
    if (giftStatus == "领取" || giftStatus == "马上抢") {
      if (app.globalData.isLogin) {
        activityModel.giftTake({
          merchantId: that.data.merchantId,
          activityId: that.data.activityId,
          giftId: giftId,
          startTime: that.data.startTime
        }).then(res => {
          that.setData({
            getCouponModel: true
          })
        }).catch(err => {
          wx.showToast({
            title: `${err.error}`,
            icon: 'none',
            duration: 2000
          })
          setTimeout(that.getActivityInstantDetailt, 1000);
          // that.getActivityInstantDetailt();
        })
      } else {
        that.setData({
          authShow: true
        })
      }
    }
  },
  close() {
    let that = this
    that.setData({
      getCouponModel: false
    }, function () {
      that.getActivityInstantDetailt();
    })
  },
  /**
   *微信会员信息
   */
  getUserInfo: function () {
    var that = this;
    memberModel.userInfo({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      that.setData({
        memberId: data.memberId || "", //会员ID
      }, function () {
        that.getActivityInstantDetailt();
      });
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 授权成功的回调
  loginSucceed: function () {
    this.getUserInfo()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timerName);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timerName);
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.couponDataInfo.activityName || "",
      imageUrl: this.data.shareImage,
      path: `pages/activity/robCoupon/index?merchantId=${this.data.merchantId}&shareMemberId=${this.data.memberId}&activityId=${this.data.activityId}&isShare=1`,
    }
  }
})